import os
import pandas as pd
import shutil

path = r"C:\Users\Kevin\Desktop\test"
os.chdir(path)  # 修改工作路径
file_path='C:\\Users\\Kevin\\Desktop\\test\\TEST3\\'


f=pd.read_excel('test1.xlsx')

col='三级单元'
shape = f.shape

# print(shape)
# print(f)
# head = f.head()
# print(head)


unique_set=list(set(f[col]))
# print(unique_set)
print(len(unique_set))
my_list = []
# my_list.append(f.loc[f['三级单元']=='接入维护中心'])
# print(my_list[0])
for i in unique_set:
    print(i)
    df=f.loc[f[col]==i]
    my_list.append(df)
print(unique_set)
folder_path = 'C:\\Users\\Kevin\\Desktop\\test\\TEST3'
try:
    # 删除文件夹及其内容
    shutil.rmtree(folder_path)
    print(f"文件夹 '{folder_path}' 删除成功")
except Exception as e:
    print(f"删除文件夹时发生错误: {e}")
os.mkdir(folder_path)
file_name=[]
for m in range(len(unique_set)):
    file_name.append(file_path+unique_set[m]+'.xlsx')

for m in range(len(my_list)):
    print(unique_set[m])
    my_list[m].to_excel(file_name[m], index=False)